<template>
  <div class="order-apply-invoice">
    <div ref="chartContainer" style="width: 100%; height: 400px;"></div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, watch, nextTick, ref, onBeforeUnmount, computed } from 'vue'
import type { ECharts, BarSeriesOption } from 'echarts'
import * as echarts from 'echarts'

interface ChartConfig {
  xAxisData: string[]
  yAxisNormalDataBar: number[]
  yAxisOverDataBar: number[]
}

const props = defineProps<{
  config: ChartConfig
}>()

const chartInstance = ref<ECharts | null>(null)
const chartContainer = ref<HTMLElement | null>(null)

// 计算属性确保响应式
const rawData = computed(() => [
  props.config.yAxisNormalDataBar,
  props.config.yAxisOverDataBar
])

const totalData = computed(() => {
  return rawData.value[0].map((_, index) => 
    rawData.value.reduce((sum, data) => sum + (data[index] || 0), 0))
})

const series = computed<BarSeriesOption[]>(() => {
  return ['normalUnReturnQty', 'overdueUnReturnQty'].map((name, seriesIndex) => ({
    name: name === 'normalUnReturnQty' ? '正常待还回调箱量' : '超期待还回调箱量',
    type: 'bar',
    stack: 'total',
    barWidth: '60%',
    label: {
      show: true,
      formatter: (params: any) => {
        const value = params.value as number
        return totalData.value[params.dataIndex] <= 0 
          ? '0' 
          : `${Math.round(value)}`
      }
    },
    data: rawData.value[seriesIndex].map((value, dataIndex) => 
      totalData.value[dataIndex] <= 0 ? 0 : value
    ),
    // label: {
    //     show: true,
    //     formatter: (params: any) => Math.round(params.value * 1000) / 10 + '%'
    // },
    // data: rawData.value[seriesIndex].map((d, did) =>totalData[did] <= 0 ? 0 : d / totalData[did]),

    emphasis: {
      itemStyle: {
        shadowBlur: 10,
        shadowOffsetX: 0,
        shadowColor: 'rgba(0, 0, 0, 0.5)'
      }
    }
  }))
})

const chartOption = computed(() => ({
  legend: {
    right: '50px',
    top: '30px',
    selectedMode: false
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  yAxis: {
    type: 'value',
    // axisLabel: {
    //   formatter: (value: number) => `${value * 100}%`
    // }
  },
  xAxis: {
    type: 'category',
    data: Array.from(props.config.xAxisData)
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    },
    formatter: (params: any) => {
      const [normal, overdue] = params as any[]
      const total = normal.value + overdue.value
      return `
        <div>${normal.axisValue}</div>
        <div>${normal.marker} ${normal.seriesName}: ${Math.round(normal.value * 1000) / 10}%</div>
        <div>${overdue.marker} ${overdue.seriesName}: ${Math.round(overdue.value * 1000) / 10}%</div>
        <div>总计: ${Math.round(total * 1000) / 10}%</div>
      `
    }
  },
  series: series.value
}))

const initChart = () => {
  if (!chartInstance.value && chartContainer.value) {
    chartInstance.value = echarts.init(chartContainer.value)
    window.addEventListener('resize', handleResize)
  }
  chartInstance.value?.setOption(chartOption.value)
}

const handleResize = () => {
  chartInstance.value?.resize()
}

watch(() => props.config, () => {
  nextTick(initChart)
}, { deep: true })

onMounted(() => {
  nextTick(initChart)
})

onBeforeUnmount(() => {
  if (chartInstance.value) {
    window.removeEventListener('resize', handleResize)
    chartInstance.value.dispose()
    chartInstance.value = null
  }
})
</script>

<style lang="scss" scoped>
.order-apply-invoice {
  width: 100%;
  height: 100%;
}
</style>